package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;


    @RequestMapping("/list")
    @RequirePermission(name = "角色查询",expression ="role:list" )
    public String list(Model model, QueryObject qo){
        PageResult<Role> pageResult = roleService.query(qo);
        List<Role> roles = roleService.listAll();



        model.addAttribute("pageResult",pageResult);
        return "role/list";
    }



    @RequestMapping("/delete")
    @ResponseBody
    @RequirePermission(name = "角色删除",expression = "role:delete")
    public JsonResult delete(Long id){
        try {
            roleService.delete(id);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult("删除失败",false);
        }

    }




    @RequestMapping("/input")
    @RequirePermission(name = "角色添加",expression = "role:input")
    public String input(Long roleId, Model model){


        if(roleId!=null){

            Role role = roleService.get(roleId);

            List<Permission> selfPermissions = permissionService.selectByRoleId(roleId);

            role.setPermissions(selfPermissions);

            model.addAttribute("role",role);

        }
        List<Permission>       allPermissions = permissionService.listAll();

        model.addAttribute("permissions",allPermissions);
        return "role/input";
    }




    @RequestMapping("saveOrUpdate")
    @RequirePermission(name = "角色保存或修改",expression = "role:saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){
        if (role.getId()==null){
            roleService.save(role,ids);
        }else{
            roleService.update(role,ids);
        }
        return "redirect:/role/list.do";
    }

}
